<!-- DataManage.vue -->
<template>
  <div id="app">
    <header>
        <h1>设备管理</h1>
        <router-link to="/" class="back-button">返回主页面</router-link>
      </header>
      <div class="buju">
      <div class="search-container">
      <input type="text" v-model="searchQuery" placeholder="搜索设备..." />
    </div>
    <form @submit.prevent="addDevice" class="add-device-form">
      <input type="text" v-model="newDevice.name" placeholder="设备名称" required />
      <select v-model="newDevice.type" required>
        <option value="风扇">风扇</option>
        <option value="空调">空调</option>
        <option value="电脑">电脑</option>
        <option value="照明灯">照明灯</option>
        <option value="烟雾报警器">烟雾报警器</option>
        <option value="监控器">监控器</option>
      </select>
      <select v-model="newDevice.address" required>
        <option value="实验室215">实验室215</option>
        <option value="实验室225">实验室225</option>
        <option value="实验室216">实验室216</option>
        <option value="实验室226">实验室226</option>
      </select>
      <select v-model="newDevice.state" required>
    <option value="未接入">未接入</option>
    <option value="已接入">已接入</option>
  </select>
      <button type="submit">添加设备</button>
    </form>
  </div>
  <div class="buju2">
    <div class="buju3">
    <!-- 设备列表表格 -->
    <table class="stats-table">
      <thead>
        <tr>
          <th>名称</th>
          <th>类型</th>
          <th>地址</th>
          <th>接入状态(是否接入涂鸦或相关平台)</th>
          <th>开关状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="device in paginatedDevices" :key="device.id">
  <td>{{ device ? device.name : '未知设备' }}</td>
  <td>{{ device.type || '未知类型' }}</td>
  <td>{{ device.address || '未知地址' }}</td>
  <td>{{ device.state || '未知状态' }}</td>
  <td>
    <template v-if="device.state === '未接入'">
      无
    </template>
    <template v-else>
      <button @click="toggleSwitch(device.id)">
        {{ device.switch === '关' ? '关' : '开' }}
      </button>
    </template>
  </td>
          <td>
            <button @click="editDevice(device.id)">编辑</button>
            <button @click="deleteDevice(device.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
<!-- 分页控件 -->
<div class="pagination">
  <ul>
    <!-- 上一页链接 -->
    <a v-if="currentPage > 1" href="#" @click.prevent="changePage(currentPage - 1)">上一页</a>
    
    <!-- 分页数字 -->
    <a v-for="index in pageCount" :key="index" :class="{ active: currentPage === index }" href="#" @click.prevent="changePage(index)">
      {{ index }}
    </a>
    
    <!-- 下一页链接 -->
    <a v-if="currentPage < pageCount" href="#" @click.prevent="changePage(currentPage + 1)">下一页</a>
  </ul>
</div>
</div>
      <table class="stats-table stats-second">
        <thead>
          <tr>
            <th>统计项</th>
            <th>数值</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(value, key) in stats" :key="key">
            <td>{{ key }}</td>
            <td>{{ value }}</td>
            <td><button @click="editStats(key)">编辑</button></td>
          </tr>
        </tbody>
      </table>
    </div>
      <!-- 添加模态框结构 -->
  <div v-show="isEditModalVisible" class="edit-modal">
    <div id="editModal" class="modal-content">
      <span class="close" @click="closeModal">&times;</span>
      <h2>编辑设备信息</h2>
      <form @submit.prevent="updateDevice">
        <input type="text" v-model="editedDevice.name" placeholder="设备名称" required />
        <select v-model="editedDevice.type" required>
          <option value="风扇">风扇</option>
        <option value="空调">空调</option>
        <option value="电脑">电脑</option>
        <option value="照明灯">照明灯</option>
        <option value="烟雾报警器">烟雾报警器</option>
        <option value="监控器">监控器</option>
        </select>
        <select v-model="editedDevice.address" required>
          <option value="实验室215">实验室215</option>
        <option value="实验室225">实验室225</option>
        <option value="实验室216">实验室216</option>
        <option value="实验室226">实验室226</option>
        </select>
        <select v-model="editedDevice.state" required>
          <option value="未接入">未接入</option>
          <option value="已接入">已接入</option>
        </select>
        <button type="submit">更新设备</button>
      </form>
    </div>
  </div>
    </div>
    </template>
    
    <script>
    import { reactive, onMounted, ref, computed} from 'vue';
    import axios from 'axios';
    
    export default {
      setup() {
        const stats = reactive({ total_devices: 0, total_undevices: 0, today_usage_time: 0 });
        const devices = reactive([]);
      const editedDevice = reactive({});
      const currentPage = ref(1);
      const pageSize = ref(10); // 每页显示的设备数量
      const searchQuery = ref(''); // 存储搜索关键词的响应式变量
      const newDevice = reactive({
        name: '',
        type: '风扇', // 默认类型为风扇
        address: '实验室215', // 默认地址为实验室215
        state: '未接入', // 默认状态为未接入
        switch: '关'
      });
      const isEditModalVisible = ref(false); // 控制模态框显示的响应式属性
      const fetchDevices = async () => {
    try {
      const response = await axios.get('/api/devices');
      // 直接使用 device.type 和 device.address，不再需要映射
      devices.splice(0, devices.length, ...response.data);
    } catch (error) {
      console.error("Error fetching devices: ", error);
    }
  };
  // 计算分页数组，用于生成分页控件
const pageCount = computed(() => {
  return Math.ceil(devices.length / pageSize.value);
});

// 根据当前页码过滤设备列表
const paginatedDevices = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredDevices.value.slice(start, end);
});

// 改变页码的方法
const changePage = (newPage) => {
  if (searchQuery.value.trim() === '') {
    // 如果搜索框为空，则更新页码
    currentPage.value = newPage;
  } else {
    // 如果搜索框有内容，重置为第一页
    currentPage.value = 1;
  }
};
      const addDevice = async () => {
    try {
      // 确保发送的数据包含 typeId 和 addressId 属性
      const deviceSwitch = newDevice.state === '未接入' ? '无' : '关';
      await axios.post('/api/devices', {
        name: newDevice.name,
        type: newDevice.type,
        address: newDevice.address,
        state: newDevice.state,
        switch: deviceSwitch,
      });
      fetchDevices(); // 刷新设备列表
      if (newDevice.state === '已接入') {
        stats.total_devices++; // 增加已接入设备计数
      } else {
        stats.total_undevices++; // 增加未接入设备计数
      }
      newDevice.name = ''; // 清空表单
      newDevice.type = '风扇'; // 重置类型选择
      newDevice.address = '实验室215'; // 重置地址选择
      newDevice.state = '未接入'; // 重置状态选择
      if (newDevice.state === '未接入') {
      newDevice.switch = ''; // 重置开关状态为无
    } else {
      newDevice.switch = '关';
    }
    } catch (error) {
      console.error("Error adding device: ", error);
      alert("添加设备失败,请检查name是否相同。");
    }
  };
      const deleteDevice = async (deviceId) => {
    try {
      await axios.delete(`/api/devices/${deviceId}`);
      const index = devices.findIndex(d => d.id === deviceId);
      if (index !== -1) {
        const device = devices[index];
            if (device.state === '已接入') {
                stats.total_devices--; // 减少已接入设备计数
            } else if (device.state === '未接入') {
                stats.total_undevices--; // 减少未接入设备计数
            }
            devices.splice(index, 1); // 从本地状态中移除设备
      }
      fetchDevices(); // 刷新设备列表
    } catch (error) {
      console.error("Error deleting device: ", error);
      alert("删除设备失败，请稍后重试或联系管理员。");
    }
  };
  const editDevice = (deviceId) => {
    const device = devices.find(d => d.id === deviceId);
    if (device) {
      editedDevice.id = device.id;
      editedDevice.name = device.name;
      editedDevice.type = device.type;
      editedDevice.address = device.address;
      editedDevice.state = device.state;
      isEditModalVisible.value = true; // 显示模态框
    }
  };
  const filteredDevices = computed(() => {
  return devices.filter((device) => {
    return (
      device.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      device.type.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      device.address.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      device.state.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
  });
});
  // 关闭模态框
  const closeModal = () => {
    isEditModalVisible.value = false; // 隐藏模态框
    editedDevice.name = '';
    editedDevice.type = '风扇'; // 重置为默认类型
    editedDevice.address = '实验室215'; // 重置为默认地址
    editedDevice.state = '未接入'; // 重置为默认状态
  };
  
  // 更新设备信息
  const updateDevice = async () => {
    if (!editedDevice.id) return; // 如果没有选择编辑的设备，则直接返回
    try {
      // 注意：这里假设您的后端接受的字段与前端发送的字段匹配
      await axios.put(`/api/devices/${editedDevice.id}`, {
        id: editedDevice.id, 
        name: editedDevice.name,
        type: editedDevice.type,
        address: editedDevice.address,
        state: editedDevice.state,
      }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
      closeModal(); // 关闭模态框
      fetchDevices(); // 刷新设备列表
    } catch (error) {
      console.error("Error updating device: ", error);
      alert("更新设备失败，请稍后重试或联系管理员。");
    }
  };
  const fetchStats = async () => {
    try {
      const response = await axios.get('/api/stats');
      stats.total_devices = response.data.total_devices;
      stats.total_undevices = response.data.total_undevices;
      stats.today_usage_time = response.data.today_usage_time;
    } catch (error) {
      console.error("Error fetching stats: ", error);
    }
  };
  const toggleSwitch = async (deviceId) => {
    try {
      const device = devices.find(d => d.id === deviceId);
      if (!device) {
        console.error("Device not found");
        return;
      }
      // 切换开关状态
      const newSwitchState = device.switch === '开' ? '关' : '开';
      // 发送请求到后端更新状态
      await axios.put(`/api/devices/${deviceId}/switch`, { switch: newSwitchState });
      // 直接在本地更新设备状态
      device.switch = newSwitchState;
    } catch (error) {
      console.error("Error toggling switch: ", error);
      alert("操作失败，请稍后重试或联系管理员。");
    }
  };
  
  const editStats = async (statName) => {
    const num = prompt(`请输入新的 ${statName} 数量：`, stats[statName]);
    if (num !== null && !isNaN(parseInt(num))) {
      const updatedNum = parseInt(num);
      try {
        await axios.put(`/api/stats/${statName}`, {
          num: updatedNum
        }, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        stats[statName] = updatedNum; // 更新前端状态
      } catch (error) {
        console.error("Error updating stats: ", error);
        alert("更新失败，请稍后重试或联系管理员。");
      }
    } else {
      alert("请输入有效的数字。");
    }
  };
    
  onMounted(() => {
    fetchStats();
    fetchDevices();
    searchQuery.value = '';
  });
  
    
  return {
    stats,
    editStats,
    newDevice,
    devices,
    addDevice,
    fetchDevices,
    deleteDevice,
    toggleSwitch,
    editedDevice,
    editDevice,
    updateDevice,
    closeModal,
    isEditModalVisible,
    filteredDevices,
    searchQuery,
    pageCount,
    paginatedDevices,
    changePage,
  };
      }
    }
    </script>
  <style  scoped lang="less">

header{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 0.7rem;
    padding: 0 20px;
    width: 100%;
    h1{
      font-size:0.8rem;
      color:#fff;
      text-align:center;
      line-height:1rem;
    }
  }
  .back-button {
  padding: 0.2rem; /* 按钮内边距 */
  font-size: 0.2rem;
  background-color: #00e1ffb5; 
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.3s; /* 背景颜色变化的过渡效果 */
  position: absolute;
  top: 0.4rem;
  right: 0.5rem;
}

.back-button:hover {
  background-color: #00b7ff; /* 鼠标悬浮时的按钮背景颜色 */
}




.stats-table {
  width: 100%;
  border-collapse: collapse;
  margin: 2px 0;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加轻微的阴影效果 */
}

.stats-table th,
.stats-table td {
  padding: 8px;
  text-align: left;
  border: 1px solid #ddd; /* 明显的分割线 */
}

.stats-table thead {
  background-color: #f2f2f2; /* 标题行背景色 */
  color: #333; /* 标题行文字颜色 */
}

.stats-table tbody tr {
  background-color: #ffffff; /* 内容行背景色统一为白色 */
  transition: background-color 0.3s; /* 平滑的背景色变化 */
}

.stats-table tbody tr:hover {
  background-color: #eaeaea; /* 鼠标悬浮时的背景色变化 */
}

.stats-table button {
  padding: 4px 8px;
  margin-right: 5px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.stats-table button:hover {
  background-color: #45a049;
}

.stats-table button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}


//搜索框
.search-container {
  position: relative;
  margin: 20px 0; /* 根据需要调整外边距 */
}

.search-container input {
  width: 100%;
  padding: 10px 15px; /* 内边距，使输入框内部文本与边框保持一定距离 */
  font-size: 16px; /* 字体大小 */
  border: 1px solid #ddd; /* 边框颜色 */
  border-radius: 24px; /* 圆角边框 */
  outline: none; /* 点击时去除默认的轮廓 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 轻微的阴影效果 */
  transition: box-shadow 0.3s; /* 阴影变化的过渡效果 */
}

.search-container input:focus {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 输入框聚焦时更明显的阴影 */
}

//添加设备
/* 添加设备表单样式 */
.add-device-form {
  margin: 20px 0; /* 根据需要调整外边距 */
}

.add-device-form input,
.add-device-form select {
  width: 20%; /* 宽度充满父容器 */
  padding: 10px; /* 内边距 */
  margin-bottom: 10px; /* 下边距 */
  font-size: 16px; /* 字体大小 */
  border: 1px solid #ddd; /* 边框颜色 */
  border-radius: 24px; /* 圆角边框 */
  outline: none; /* 点击时去除默认的轮廓 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 轻微的阴影效果 */
  transition: box-shadow 0.3s; /* 阴影变化的过渡效果 */
}

.add-device-form input:focus,
.add-device-form select:focus {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 输入框聚焦时更明显的阴影 */
}

.add-device-form button {
  padding: 10px 15px; /* 按钮内边距 */
  font-size: 16px; /* 字体大小 */
  color: #fff; /* 文字颜色 */
  background-color: #4CAF50; /* 背景颜色 */
  border: none; /* 无边框 */
  border-radius: 24px; /* 圆角边框 */
  cursor: pointer; /* 鼠标悬停时显示手型图标 */
  transition: background-color 0.3s; /* 背景颜色变化的过渡效果 */
}

.add-device-form button:hover {
  background-color: #45a049; /* 鼠标悬浮时的按钮背景颜色 */
}


.buju{
display: flex;
flex-direction: row;
justify-content: space-between;
margin-right: 7rem;
}

.buju2{
  display: flex;
  width: 100%;
  height: 9.5rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.buju3 {
  flex: 60% 0 0; /* 设备表占60%，不允许缩小 */
  max-width: 60%;
  padding: 20px; /* 内边距 */
}

.pagination {
  display: flex; /* 使用flex布局 */
  padding: 0;
  margin-top: 0.25rem;
  list-style: none;
}

.pagination a {
  margin: 0 5px; /* 分页项之间的间距 */
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  text-decoration: none;
  color: #333;
  background-color: #f8f8f8;
  transition: background-color 0.3s, color 0.3s;
}

.pagination a:hover,
.pagination a.active {
  background-color: #4CAF50;
  color: white;
}

.pagination a.disabled {
  opacity: 0.5;
  pointer-events: none;
}


.stats-table.stats-second {
  flex: 0 0 39%; /* 统计表占30%，不允许缩小 */
  max-width: 39%;
}



/* 模态框样式 */
.edit-modal {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
}

.modal-content {
  position: relative;
  width: 90%;
  max-width: 400px; /* 最大宽度 */
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 24px;
  cursor: pointer;
}

/* 模态框表单样式 */
.modal-content form {
  display: flex;
  flex-direction: column;
}

.modal-content form h2 {
  margin-bottom: 20px;
  text-align: center;
}

.modal-content form input,
.modal-content form select {
  padding: 10px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.modal-content form button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.modal-content form button:hover {
  background-color: #45a049;
}

  </style>